<template>
	<view @click="toggle" class="switch" :class="{'switch--disabled':props.disabled}" :style="{width:2*size+'px',height:switchHeight,borderRadius:size+'px',backgroundColor:currentValue===props.activeValue?props.activeColor:props.inactiveColor}">
		<view class="switch__circle" :style="{width:props.size+'px',height:props.size+'px',transform:currentValue===props.activeValue?`translateX(${size}px)`:`translateX(0)`}"></view>
	</view>
</template>

<script setup>
	import {computed, watch, ref} from 'vue'
	import propsData from './props.js'
	const props = defineProps(propsData)
	const emits = defineEmits(['update:modelValue', 'change'])
	
	const switchHeight = computed(() => {
		// #ifdef APP-NVUE
		return props.size + 2 + 'px'
		// #endif
		// #ifndef APP-NVUE
		return props.size + 'px'
		// #endif
	})
	const currentValue = ref(false)
	
	watch(() => props.modelValue, (newVal) => {
		currentValue.value = newVal
	}, {immediate: true})

	
	function toggle() {
		if (!props.disabled) {
			const changeResult = currentValue.value === props.activeValue ? props.inactiveValue : props.activeValue;
			if (props.handleChange && typeof props.handleChange === 'function') {
				// 先变化样式
				currentValue.value = changeResult
				// 处理结果
				const result = props.handleChange(changeResult)
				if (typeof result === 'object') {
					result.then((res) => {
						if(res === changeResult) toggleValue(res)   // 确定切换
						else setTimeout(()=>toggleValue(res),300)     // 不切换，切换至结果result
					}).catch((err) => {
						console.log(err);
						setTimeout(()=>toggleValue(changeResult === props.activeValue ? props.inactiveValue : props.activeValue),300)
					})
				} else if (typeof result === 'boolean') {
					if(result === changeResult) toggleValue(result)   // 确定切换
					else setTimeout(()=>toggleValue(result),300)     // 不切换，切换至结果result
				}
			} else {
				toggleValue(changeResult)
			}
		}
	}
	function toggleValue(changeResult) {
		currentValue.value = changeResult
		emits('update:modelValue', currentValue.value)
		emits('change', currentValue.value)
	}
</script>

<style lang="scss" scoped>
	.switch {
		position: relative;
		border-width: 1px;
		border-color: rgba(0, 0, 0, 0.1);
		border-style: solid;
		transition: background-color 0.3s;
		/* #ifndef APP-NVUE */
		box-sizing: content-box;
		/* #endif */
	}

	.switch--disabled {
		opacity: 0.3;
	}

	.switch__circle {
		position: absolute;
		left: 0;
		top: 0;
		background-color: #fff;
		border-radius: 50%;
		/* #ifndef APP-NVUE */
		box-shadow: 0 3px 1px 0 rgba(0, 0, 0, 0.05), 0 2px 2px 0 rgba(0, 0, 0, 0.1), 0 3px 3px 0 rgba(0, 0, 0, 0.05);
		/* #endif */
		/* #ifdef APP-NVUE */
		box-shadow: 1px 0 0px 0 rgba(0, 0, 0, 0.05);
		/* #endif */
		transition: transform 0.3s;
	}
</style>